package org.linlinjava.litemall.admin.wx.handler;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.linlinjava.litemall.admin.wx.builder.TextBuilder;
import org.linlinjava.litemall.core.redis.RedisCache;
import org.linlinjava.litemall.core.template.WxMpMsgTemplateService;
import org.linlinjava.litemall.db.domain.WxUser;
import org.linlinjava.litemall.db.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;


@Component
public class ButtonHandler extends AbstractHandler {

	@Autowired
	private WxUserService wxUserService;
	@Autowired
	private WxMpMsgTemplateService wxMpMsgTemplateService;
	@Autowired
	private RedisCache redisCache;

	
  @Override
  public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                  Map<String, Object> context, WxMpService wxMpService,
                                  WxSessionManager sessionManager) throws WxErrorException {
	// 获取微信用户基本信息
	WxMpUser userWxInfo = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
	//查询缓存10分钟内是否有催单，如果有提示用户不可重复催单，如果没有进入催单流程
	String res = (String) redisCache.get("reminder_"+userWxInfo.getOpenId());
	if(!StringUtils.isEmpty(res)) {
		if(res.equals("true")) {
			return new TextBuilder().build("您已提交过催单，请不要重复提交，请10分钟后再试！", wxMessage, wxMpService);
		}
	}
	//将催单次数缓存，防止多次催单
	redisCache.setCacheObject("reminder_"+userWxInfo.getOpenId(), "true", 10 , TimeUnit.MINUTES);
	String content = "";
	//先查询是否已存在
    WxUser wxUser = wxUserService.getOneUser(userWxInfo.getOpenId());
    if(wxUser == null) {
    	content = "订单信息未查询到！(只支持查询 快当外卖)";
    }else {
    	content = "客官稍等，系统正在查询订单信息..";
    	wxMpMsgTemplateService.pushReminderToUser(wxUser);
    }
	return new TextBuilder().build(content, wxMessage, wxMpService);
  }

}